import { useUserStore } from '@/store/user'

let socket = null

let socketEmitter = {}

export const useSocket = (params?) => {
  return new Promise((resolve, reject) => {
    try {
      const { type, callback } = params || {}
      if (type) socketEmitter[type] = callback
      if (socket) return resolve(socket)
      const userStore = useUserStore()
      const userInfo = computed(() => userStore.userInfo)
      const sorketUrl = `ws://${userInfo.value.ip}:${userInfo.value.port}`
      console.log('sorketUrl', sorketUrl)
      socket = uni.connectSocket({
        url: sorketUrl,
        success(data) {
          console.log('connectSocket', data)
          console.log('socket', socket)
          // uni.onSocketMessage((res) => {
          //   const data = JSON.parse(res.data)
          //   console.log('data', data)
          //   const fun = socketEmitter[data.Type]
          //   console.log('fun', fun)
          //   fun && fun(data.Data)
          // })
          // resolve(socket)
        },
      })
      uni.onSocketOpen((res) => {
        console.log('onSocketOpen', res)
        socket.closess = () => {
          console.log('closeSocket')
          uni.closeSocket({
            code: 1000,
            complete: (res) => {
              console.log('closeSocket complete', res)
            },
          })
        }
        uni.onSocketMessage((res) => {
          const data = JSON.parse(res.data)
          console.log('data', data)
          const fun = socketEmitter[data.Type]
          console.log('fun', fun)
          fun && fun(data.Data)
        })
        return resolve(socket)
      })
      uni.onSocketClose((res) => {
        socket = null
        socketEmitter = {}
        console.log('onSocketClose', res)
      })

      uni.onSocketError(function (res) {
        console.log('WebSocket！', res)
        uni.showModal({
          title: '提示',
          content: '数据异常，请重启app',
        })
      })
    } catch (error) {
      console.log('error', error)
      reject(error)
    }
  })
}
